package com.qianfeng.iot.mqtt.config;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.iot.sdk.bean.mqtt.MqttProperties;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import java.util.List;

/**
 * Created by Jackiechan on 2022/8/16 21:34
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Configuration
@EnableConfigurationProperties({MqttProperties.class})
public class MqttConfig {

    private MqttProperties mqttProperties;

    @Autowired//封装我们mqtt属性的对象,将我们的配置文件中的属性设置进来
    public void setMqttProperties(MqttProperties mqttProperties) {

        this.mqttProperties = mqttProperties;
    }

    /**
     * 创建我们的连接属性
     * @return
     */
    @Bean
    public MqttConnectOptions options() {
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setServerURIs(new String[]{mqttProperties.getUrl()});
        if (mqttProperties.getAuthType() == MqttProperties.AuthTypeEnum.USERNAME) {
            connectOptions.setUserName(mqttProperties.getUsername());
            connectOptions.setPassword(mqttProperties.getPassword().toCharArray());
        }
        return connectOptions;
    }

    /**
     * 设置我们的mqtt的连接工厂
     * @param options
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory(MqttConnectOptions options) {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(options);
        return factory;
    }

    /**
     * 接收消息的通道
     * @return
     */
    @Bean
    public MessageChannel messageInputChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageProducer mqttInbound(MessageChannel messageInputChannel,MqttPahoClientFactory mqttPahoClientFactory) {
        List<MqttProperties.Topic> receiveTopics = mqttProperties.getReceiveTopics();
        //设置我们所有的想要收的topic
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(mqttProperties.getClient() + "_in", mqttPahoClientFactory, receiveTopics.stream().map(MqttProperties.Topic::getName).toArray(String[]::new));
        adapter.setConverter(new DefaultPahoMessageConverter());
        //设置qos
        adapter.setQos(receiveTopics.stream().mapToInt(MqttProperties.Topic::getQos).toArray());
        adapter.setOutputChannel(messageInputChannel);
        return adapter;
    }

    /**
     * 发消息的通道
     * @return
     */
    @Bean
    public MessageChannel messageOutputChannel() {
        return new DirectChannel();
    }


    @Bean
    @ServiceActivator(inputChannel = "messageOutputChannel")
    public MessageHandler mqttOutbound(MqttPahoClientFactory mqttPahoClientFactory) {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getClient() + "_out", mqttPahoClientFactory);
        messageHandler.setDefaultTopic(mqttProperties.getDefaultSendTopic().getName());
        messageHandler.setDefaultQos(mqttProperties.getDefaultSendTopic().getQos());
        messageHandler.setAsync(true);
        return messageHandler;
    }

}
